package interceptor;

import entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石小俊
 * 登录检查拦截器
 * 要求访问当前springmvc服务器中的所有资源均必须登录
 * 但是登录相关的业务无需登录
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    /**
     * 进入Handler处理核心业务逻辑之前
     * @param request
     * @param response
     * @param handler
     * @return  是否放行。true:放行,false:不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        System.out.println("1   "+request);
        System.out.println("2   "+handler);
        System.out.println("3   "+response);
        User user= (User) request.getSession().getAttribute("user");
        if(user ==null){
            request.setAttribute("loginMsg","您尚未登录，请先登录");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return false;
        }
        return true;
    }

    /**
     * 进入Handler处理核心业务逻辑之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{
        System.out.println("LogHandlerInterceptor.postHandle");
    }

    /**
     * 返回响应之前
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{
        System.out.println("LogHandlerInterceptor.afterCompletion");
    }
}
